﻿using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using Kang.ExtendMethod;
using Microsoft.Win32;
using NetVips;

namespace Kang.Test.Framework.WPF
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //AppendMsg($"临时Token：{App.TempToken}");

            //App.GetSliceReadToken("40e6a596d44038d394aaf7ec5fe3d622").ContinueWith(t =>
            //{
            //    if (t.Result == null) 
            //    {
            //        return;
            //    }
            //    var r = t.Result.Data;
            //    r.ForEach(x =>
            //    {
            //        AppendMsg($"切片阅读Token：{x.Token}");
            //    });
            //});
            NetVips.NetVips.Init();
            Image image = NetVips.Image.NewFromFile(@"D:\数字切片\通用SVS\456123.svs");
            image.Dzsave(@"C:\Users\kang\Desktop\svs_tiles", "svs");
            NetVips.NetVips.Shutdown();
        }

        private void btn_select_section_file_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.AddExtension = true;
            dialog.Multiselect = false;
            dialog.InitialDirectory = @"D:\数字切片";
            dialog.Filter = "SVS切片|*.svs|江丰切片|*.kfb|麦克奥迪|*.mdsx|迪麦克斯|*.dmetrix";
            if(dialog.ShowDialog() != true)
            {
                return;
            }
            txt_section_filepath.Text = dialog.FileName;
            AppendMsg($"切片地址：{txt_section_filepath.Text}");
        }

        private void btn_get_section_id_Click(object sender, RoutedEventArgs e)
        {
            var filePath = txt_section_filepath.Text;
            if (filePath.AsFilePathAndExists() != true)
            {
                AppendMsg($"文件不存在，地址：{filePath}");
                return;
            }
            var fileInfo = new FileInfo(filePath);
            App.SliceId(fileInfo.Name, fileInfo.Length, App.SliceFilePath(fileInfo.Name)).ContinueWith(t =>
            {
                var res = (SliceIdDto)(t.Result).Data;
                AppendMsg($"切片Id：{res.Id}{Environment.NewLine}切片地址：{res.Path}");
            });
        }

        private void btn_get_section_chunk_Click(object sender, RoutedEventArgs e)
        {
            var filePath = txt_section_filepath.Text;
            if (filePath.AsFilePathAndExists() != true)
            {
                AppendMsg($"文件不存在，地址：{filePath}");
                return;
            }
            var fileInfo = new FileInfo(filePath);
            int[] chunks;
            ChunkSectionFile(txt_section_filepath.Text, out chunks);
            int[] isUpload = new int[chunks.Length];

            App.SliceId(fileInfo.Name, fileInfo.Length, App.SliceFilePath(fileInfo.Name)).ContinueWith(t =>
            {
                var idRes = (SliceIdDto)(t.Result).Data;
                AppendMsg($"切片Id：{idRes.Id}{Environment.NewLine}切片地址：{idRes.Path}");
                Task.Run(() =>
                {
                    for (int i = 0; i < chunks.Length; i++)
                    {
                        var chunkRes = App.CheckSliceChunk(fileInfo.Name, idRes.Id, chunks.Length, i + 1, (long)App.ChunkSize, chunks[i], fileInfo.Length).Result;
                        AppendMsg($"分片Num：{(i + 1)}{Environment.NewLine}Code：{chunkRes.Code}{Environment.NewLine}Msg：{chunkRes.Message}");
                        if ("0000".Equals(chunkRes.Code))
                        {
                            isUpload[i] = 1;
                        }
                        else
                        {
                            isUpload[i] = 0;
                        }
                    }
                });
            });
        }

        private void btn_upload_section_chunk_Click(object sender, RoutedEventArgs e)
        {
            var filePath = txt_section_filepath.Text;
            if (filePath.AsFilePathAndExists() != true)
            {
                AppendMsg($"文件不存在，地址：{filePath}");
                return;
            }
            var fileInfo = new FileInfo(filePath);
            int[] chunks;
            ChunkSectionFile(txt_section_filepath.Text, out chunks);
            int[] isUpload = new int[chunks.Length];

            App.SliceId(fileInfo.Name, fileInfo.Length, App.SliceFilePath(fileInfo.Name)).ContinueWith(t =>
            {
                var idRes = (SliceIdDto)(t.Result).Data;
                AppendMsg($"切片Id：{idRes.Id}{Environment.NewLine}切片地址：{idRes.Path}");
                Task.Run(() =>
                {
                    var datas = new byte[(int)App.ChunkSize];
                    Response chunkUploadRes;
                    for (int i = 0; i < chunks.Length; i++)
                    {
                        var chunkRes = App.CheckSliceChunk(fileInfo.Name, idRes.Id, chunks.Length, i + 1, (long)App.ChunkSize, chunks[i], fileInfo.Length).Result;
                        AppendMsg($"分片Num：{(i + 1)}{Environment.NewLine}Code：{chunkRes.Code}{Environment.NewLine}Msg：{chunkRes.Message}");
                        if ("0000".Equals(chunkRes.Code))
                        {
                            isUpload[i] = 1;
                        }
                        else
                        {
                            isUpload[i] = 0;
                        }
                    }
                    using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        for (int i = 0; i < isUpload.Length; i++)
                        {
                            if (isUpload[i] == 1)
                            {
                                continue;
                            }
                            fs.Position = (int)App.ChunkSize * (i);
                            fs.Read(datas, 0, (int)App.ChunkSize);
                            using (Stream ms = new MemoryStream(datas))
                            {
                                chunkUploadRes = App.UploadSliceChunk(fileInfo.FullName, idRes.Id, chunks.Length, i + 1, (long)App.ChunkSize, chunks[i], fileInfo.Length, ms).Result;
                            }
                            AppendMsg($"分片Num：{(i + 1)}{Environment.NewLine}上传返回Code：{chunkUploadRes.Code}{Environment.NewLine}Msg：{chunkUploadRes.Message}");
                        }
                    }
                });
            });
        }

        void ChunkSectionFile(string filepath, out int[] chunks)
        {
            var fileInfo = new FileInfo(filepath);
            var chunkSize = App.ChunkSize;
            var totalChunks = (int)Math.Ceiling(fileInfo.Length / chunkSize);
            chunks = new int[totalChunks];
            for (int i = 0; i < totalChunks; i++)
            {
                if (i < totalChunks - 1)
                {
                    chunks[i] = (int)chunkSize;
                }
                else
                {
                    chunks[i] = (int)(fileInfo.Length - (chunkSize * (totalChunks - 1)));
                }
            }
        }

        void AppendMsg(string msg)
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                txt_status.AppendText($"{DateTime.Now.GetString("yyyy/MM/dd HH:mm:ss.ffff")}{Environment.NewLine}{msg}{Environment.NewLine}{Environment.NewLine}");
                txt_status.ScrollToEnd();
            }));
        }
    }
}
